package cn.cmkj.auction.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.AuctionListAdapter;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.http.Auction;
import cn.cmkj.auction.ui.AuctionDetailActivity;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.ItemClickSupport;
import cn.cmkj.auction.widget.swipeRecyclerView.MySwipeMenuRecyclerView;

/**
 * Created by cunguoyao on 2018/4/23.
 */
@ContentView(R.layout.fragment_main_paimai_list)
public class PaimaiListFragment extends BaseFragment implements MySwipeMenuRecyclerView.OnLoadListener {

    private View view;
    @ViewInject(R.id.swipeRecyclerView)
    private MySwipeMenuRecyclerView swipeRecyclerView;

    private List<Auction> mData;
    private AuctionListAdapter auctionListAdapter;
    private boolean requesting = false;
    private int page = 1;
    private int type;//1今日拍卖 2明日展览 3历史拍卖

    public static PaimaiListFragment create(int type) {
        PaimaiListFragment f = new PaimaiListFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getInt("type", 1);
        mData = new ArrayList<>();
        auctionListAdapter = new AuctionListAdapter(getActivity(), mData);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(view == null) {
            view = x.view().inject(this, inflater, container);
        }
        swipeRecyclerView.getRecyclerView().setLayoutManager(new GridLayoutManager(getActivity(), 1));
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setLongPressDragEnabled(true); // 开启拖拽。
        //((SwipeMenuRecyclerView)swipeRecyclerView.getRecyclerView()).setItemViewSwipeEnabled(true); // 开启滑动删除。
        swipeRecyclerView.setAdapter(auctionListAdapter);
        ItemClickSupport.addTo(swipeRecyclerView.getRecyclerView()).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, View itemView, int position) {
                Auction item = auctionListAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), AuctionDetailActivity.class);
                intent.putExtra("auction", item);
                startActivity(intent);
            }
        });
        swipeRecyclerView.setOnLoadListener(this);
        swipeRecyclerView.setRefreshing(true);
        return view;
    }

    @Override
    public void onRefresh() {
        if(!requesting) {
            page = 1;
            mData.clear();
            auctionListAdapter.notifyDataSetChanged();
            fetchData();
        }
    }

    @Override
    public void onLoadMore() {
        if(!requesting) {
            page = page +1;
            LogUtil.e("--onLoadMore:page=" + page);
            fetchData();
        }
    }

    public void fetchData() {
        requesting = true;
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.auctionList);
        params.addParameter("type", String.valueOf(type));
        params.addParameter("page_num", page);
        params.addParameter("page_size", Urls.pageSize);
        //params.addParameter("accesstoken", user.getToken());
        //params.addParameter("member_id", user.getId());
        x.http().request(HttpMethod.POST, params, new HttpCallback(getActivity()) {
            @Override
            public void success(String s) {
                requesting = false;
                swipeRecyclerView.complete();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(s);
                    JSONObject json = jsonObject.optJSONObject("data");
                    int count = json.getInt("count");
                    ((MainPaimaiFragment)getParentFragment()).setRadioText(type, count);
                    JSONArray jsonArray = json.optJSONArray("goods");
                    List<Auction> temp = Auction.parseJsonArray(jsonArray);
                    mData.addAll(temp);
                    auctionListAdapter.notifyDataSetChanged();
                    if (Urls.pageSize > temp.size()) {
                        swipeRecyclerView.setLoadMoreEnable(false);
                    } else {
                        swipeRecyclerView.setLoadMoreEnable(true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                requesting = false;
                swipeRecyclerView.complete();
                if (ex != null) ex.printStackTrace();
                LogUtil.e("---onError-----" + "onError");
                Toast.makeText(getActivity(), TextUtils.isEmpty(msg) ? "请求失败" : msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void cancel(CancelledException cex) {
                requesting = false;
                swipeRecyclerView.complete();
                LogUtil.e("---onCancelled-----" + "onCancelled");
            }
        });
    }
}
